package com.polaris.live.ui.me

import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.polaris.live.R
import com.polaris.live.adapter.level.GameLevelBannerAdapter
import com.polaris.live.adapter.level.MeGameLevelAdapter
import com.polaris.live.common.ext.dp
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.FragmentGameLevelBinding
import com.polaris.live.popup.PreviewRichCharmPopup
import com.polaris.live.resp.back_resp.RichCharmSizeBean
import com.polaris.live.resp.back_resp.UserRichCharmLevelRewardExplainVo
import com.polaris.live.resp.back_resp.UserScorePartyGameResp
import com.zhpan.bannerview.constants.PageStyle

/**
 * GameLevelFragment
 *
 * @author Created by 半仙 on 2024/4/19/019 11:56
 */
class GameLevelFragment : BaseVbFragment<BaseViewModel, FragmentGameLevelBinding>() {

    private val mGameResp: UserScorePartyGameResp? by lazy {
        arguments?.getParcelable("game")
    }

    private val mAdapter by lazy { MeGameLevelAdapter() }

    private val mBannerAdapter by lazy { GameLevelBannerAdapter() }

    override fun initView(savedInstanceState: Bundle?) {
        ViewUtils.setMargin(
            mBinding.consBottom,
            bottomMargin = NavigationBarUtils.getNavigationBarHeight(requireContext())
        )
        val bannerList = mGameResp?.medals?.values?.toMutableList()
        mBinding.honorBanner.apply {
            registerLifecycleObserver(lifecycle)
            setAdapter(mBannerAdapter)
            setCanLoop(false)
            setRevealWidth(100.dp, 100.dp)
            setIndicatorVisibility(View.GONE)
            setPageStyle(PageStyle.MULTI_PAGE_SCALE, 0.8f)
            create(bannerList)
        }
        val findLevel = findLevel(mGameResp?.score)

        val pair = calculateProgress(findLevel)
        var ratio = 0f
        pair?.let {
            ratio = pair.second / pair.first.toFloat()
            mBinding.tvLevelInfo.text = "${pair.second}/${pair.first}"
        }
        mBinding.tvLevelInfo.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (!isDestroyView()) {
                    mBinding.tvLevelInfo.viewTreeObserver.removeOnGlobalLayoutListener(this)
                    val text = mBinding.tvLevelInfo.text.toString()
                    val textSize = mBinding.tvLevelInfo.textSize
                    val paint = Paint()
                    paint.textSize = textSize
                    val textWidth = paint.measureText(text)
                    mBinding.tvLevelInfo.setPadding(
                        ((mBinding.tvLevelInfo.measuredWidth - textWidth) * ratio).toInt(),
                        0,
                        0,
                        0
                    )
                }
            }
        })
        getShapeTextColor(findLevel.toIntOrNull()).let {
            mBinding.tvUserGameName.apply {
                textColorBuilder.setTextGradientColors(it.first, it.second).intoTextColor()
                text = "${mGameResp?.gameName} "
            }

            mBinding.tvUserGameLevel.apply {
                textColorBuilder.setTextGradientColors(it.first, it.second).intoTextColor()
                text = "Lv.$findLevel "
            }
        }
        getProgressBarColor(findLevel.toIntOrNull()).let {
            mBinding.apply {
                val levels = mGameResp?.scoreLevels?.keys?.toMutableList() ?: return
                //计算需要展示的当前开始等级和结束等级
                val lastLevel = levels.last()
                //如果还没到最后一级
                val (startLevel, endLevel) = if (findLevel < lastLevel) {
                    val indexOf = levels.indexOfFirst { it == findLevel }
                    findLevel to levels[indexOf + 1]
                } else {
                    levels[levels.size - 2] to lastLevel
                }

                tvLevelStart.text = "Lv.$startLevel"
                tvLevelStart.setTextColor(it.first)
                progressBar.progressDrawable =
                    ContextCompat.getDrawable(requireContext(), it.second)
                tvLevelEnd.text = "Lv.$endLevel"
                tvLevelEnd.setTextColor(it.first)
            }
        }

        calculateProgress(findLevel)?.let {
            mBinding.progressBar.max = it.first.toInt()
            mBinding.progressBar.progress = it.second
        }
        mBinding.gameLevelRecycler.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(context)
        }
        mAdapter.setList(mGameResp?.rules)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItemOrNull(position)?.medal ?: return@setOnItemChildClickListener
            when (view.id) {
                R.id.iv_medal -> {
                    PreviewRichCharmPopup.show(
                        requireContext(), UserRichCharmLevelRewardExplainVo(
                            content = "",
                            displayUrl = item.photoUrl,
                            effectPhotoUrl = item.pagUrl,
                            ext = JsonUtils.toJson(RichCharmSizeBean(333, 333)),
                            photoUrl = item.photoUrl,
                            rewardType = 2,
                            title = ""
                        )
                    )
                }
            }
        }
    }

    //获取等级
    private fun findLevel(score: Long?): String {
        val gameResp = mGameResp ?: return "1"
        val levels = gameResp.scoreLevels.keys.toMutableList()
        for (i in 0 until levels.size - 1) {
            //如果当前等级比第一个还小直接返回0级
            gameResp.scoreLevels[levels[i]]?.let {
                if (score != null && score < it) {
                    return "0"
                }
            }
            // 安全地检查下一等级分数阈值，如果当前分数小于下一等级的起始分数，则返回当前等级
            gameResp.scoreLevels[levels[i + 1]]?.let {
                if (score != null && score < it) {
                    return levels[i]
                }
            }
        }
        return levels.lastOrNull() ?: "0"
    }

    //获取渐变颜色
    private fun getShapeTextColor(level: Int?): Pair<Int, Int> {
        if (level == null) {
            return ColorUtils.getColor(R.color.color_ff9c6b) to ColorUtils.getColor(R.color.color_ffc5a8)
        }
        //这里ui给了等级范围 所以直接写死即可
        return when {
            level < 2 -> ColorUtils.getColor(R.color.color_ff9c6b) to ColorUtils.getColor(R.color.color_ffc5a8)
            level < 4 -> ColorUtils.getColor(R.color.color_7fb3e5) to ColorUtils.getColor(R.color.color_c1f0ff)
            else -> ColorUtils.getColor(R.color.color_ffd802) to ColorUtils.getColor(R.color.color_fff147)
        }
    }

    //获取进度条颜色和等级颜色
    private fun getProgressBarColor(level: Int?): Pair<Int, Int> {
        if (level == null) {
            return ColorUtils.getColor(R.color.color_ffb089) to R.drawable.game_level_1_progress
        }
        //这里ui给了等级范围 所以直接写死即可
        return when {
            level < 2 -> ColorUtils.getColor(R.color.color_ffb089) to R.drawable.game_level_1_progress
            level < 4 -> ColorUtils.getColor(R.color.color_9cd4ff) to R.drawable.game_level_2_progress
            else -> ColorUtils.getColor(R.color.color_fff701) to R.drawable.game_level_3_progress
        }
    }

    //计算进度条进度
    private fun calculateProgress(findLevel: String): Pair<Long, Int>? {
        val scores = mGameResp?.scoreLevels?.values?.toMutableList() ?: return null
        //根据当前等级取出对应的经验值
        val nowValue = mGameResp?.scoreLevels?.get(findLevel)
        val indexOfFirst = scores.indexOfFirst { it == nowValue }
        //当indexOfFirst 小于 size - 1的时候就可以理解为满级了
        val (lastMax, max) = if (indexOfFirst < scores.size - 1) {//得到当前升级的经验 和上一个升级的经验
            //为-1的时候就是0级的时候
            val nowMax = scores[indexOfFirst + 1]
            val last = if (indexOfFirst == -1) {
                0L
            } else {
                scores[indexOfFirst]
            }
            last to nowMax
        } else {
            0L to scores.last()
        }
        //减去之前所有的等级   这样相当于从0开始算了
        val nowScore = mGameResp?.score?.toInt() ?: 0
        val showMax = max - lastMax
        val showProgress = (nowScore - lastMax).toInt()

        return if (showMax <= 0) {
            max to if (showProgress < 0) nowScore else showProgress
        } else {
            showMax to if (showProgress < 0) nowScore else showProgress
        }
    }
}